<!--
 * @Author: zhangpeng
 * @Date: 2024-11-25 15:09:44
 * @FilePath: \scientific_research_manager_web\src\views\resultsManagement\components\Horizontal\detail.vue
 * @LastEditTime: 2025-01-17 10:58:48
 * @Description:  成果-横向项目/管理详情
-->
<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import ResultsInfo from '@/components/SheetInfo/index.vue'
import ResultAuditRecordTable from '../ResultAuditRecordTable.vue'
import { resultStatusEnum, dictEnum, projectNatureEnum } from '@/utils/constEnum'
import { getHorizontalDetailApi, getHorizontalUpdateApi, getHorizontalCreateApi } from '@/api/resultsManagement/horizontalApi'
import { approveResultsManagementApi, deleteResultsManagementApi, appraiseStandardApi, getResearchScoreApi } from '@/api/resultsManagement/index'
import { getProjectListApi } from '@/api/project'
import { ProjectBasePageVO } from '@/types/project/response'
import { SheetInfoComponent, SheetInfoFormTypeEnum } from '@/types/component'
import { HorizontalPageVO, AppraiseStandardDTO } from '@/types/resultsManagement'
import { AppStateChangeRespDTO } from '@/types/index'

const props = defineProps({
  /* 模块类型：college 学院成果管理；office 科研处成果管理；mine 我的成果； */
  moduleType: {
    type: String as PropType<'college' | 'office' | 'mine'>,
    default: 'college',
  },
})

const pageLoading = computed(() => {
  return loading.value || deleteLoading.value || updateLoading.value || createLoading.value || approveLoading.value
})

// 当前实例
const { proxy } = getCurrentInstance()

const dict = proxy.useDict(dictEnum.horizontalContractType, dictEnum.reviewOpinion)

const route = useRoute()
const router = useRouter()
// 用户信息
const userStore = useUserStore()
const achvId = ref()  //  id
const projectNameList = ref([]) //  项目名list
const projectCodeList = ref([]) //  项目编号list
const projectList = ref<ProjectBasePageVO[]>([]) //  项目list
// 审核状态
const status = ref()
const applyPerInfo = ref<{ departmentName?: string, accountCode?: string, accountName?: string }>({})
const ResultsInfoRef = ref()

// 显示删除弹框
const showDeleteDetail = ref(false)
// 显示取消保存弹框
const showCancelSave = ref(false)
// 显示提交弹框
const showSubmitSave = ref(false)
// 显示审核不通过弹框
const showDisApprove = ref(false)
// 显示审核通过弹框
const showApprove = ref(false)

const showAuditRecordTable = ref(false) // 显示审核记录


const sheetComponents = ref<SheetInfoComponent[]>([
  {
    title: '项目编号', // 需要获取后台数据
    type: SheetInfoFormTypeEnum.select,
    key: 'projectCode',
    placeholder: '项目编号',
    config: {
      options: computed(() => { return projectCodeList.value || [] }),
      allowCreate: true,
      filterable: true,
      class: 'projectCodeClass',
      sheetInfoLabelHeight: 'auto',
      sheetInfoRowMarginTop: computed(() => { return mode.value !== 'edit' ? '0px' : '4px' }),
      rules: [
        { required: true, message: '项目编号不能为空' },
      ]
    }
  },
  {
    title: '项目名称',
    type: SheetInfoFormTypeEnum.select,
    key: 'name',
    placeholder: '项目名称',
    config: {
      options: computed(() => { return projectNameList.value || [] }),
      allowCreate: true,
      filterable: true,
      class: 'projectNameClass',
      rules: [
        { required: true, message: '项目名称不能为空' },
      ]
    }
  },
  {
    title: '合同类别',
    type: SheetInfoFormTypeEnum.select,
    key: 'projectTypeId',
    placeholder: '合同类别',
    config: {
      options: computed(() => { return dict?.[dictEnum.horizontalContractType] || [] }),
      rules: [
        { required: true, message: '合同类别不能为空' },
      ]
    }
  },

  {
    title: '委托单位',
    type: SheetInfoFormTypeEnum.inputOrTextArea,
    key: 'client',
    placeholder: '请输入',
    config: {
      rules: [
        { required: true, message: '委托单位不能为空' },
      ],
      maxLength: 50,
      showWordLimit: true,
    }
  },
  //  数值[0.01-9999.99]保留两位小数
  {
    title: '经费',
    type: SheetInfoFormTypeEnum.inputNumber,
    key: 'funds',
    placeholder: '请输入',
    config: {
      rules: [
        { required: true, message: '经费不能为空' },
      ],
      min: 0.01,
      step: 0.01,
      max: 9999.99,
      suffix: '万元',
      stepStrictly: true,
      controls: false
    }
  },
  {
    title: '合同签订日期',
    type: SheetInfoFormTypeEnum.datePick,
    key: 'businessDate',
    hidden: false,
    placeholder: '请选择日期',
    config: {
      rules: [
        { required: true, message: '合同签订日期不能为空' },
      ],
      valueFormat: 'YYYY-MM-DD',
    }
  },
  {
    title: '统计年度',
    type: SheetInfoFormTypeEnum.text,
    key: 'statisticalYear',
    width: 'calc(100% - 120px)',
    cValue: '2024',
    placeholder: '请选择年份',
    config: {
      rules: [
        { required: true, message: '统计年度不能为空' },
      ],
      type: 'year',
      valueFormat: 'YYYY',
    }
  },
  
  {
    title: '科研分',
    type: SheetInfoFormTypeEnum.radio,
    key: 'researchScoreFlag',
    width: 'calc(100% - 120px)',
    cValue: false,
    config: {
      options: [
        { title: '属于科研分认定范畴', value: true },
        { title: '不属于科研分认定范畴', value: false },
      ],
      rules: [
        { required: true, message: '科研分认定范畴类型不能为空' },
      ],
    }
  },
  {
    title: '',
    type: 99,
    key: 'assessmentMethodId',
    depended: 'researchScoreFlag',
    hidden: true,
    placeholder: '请选择',
    config: {
      list: [{
        title: '计分类别',
        type: SheetInfoFormTypeEnum.select,
        key: 'scoringCategoryId',
        depended: 'researchScoreFlag',
        placeholder: '请选择计分类别',
        config: {
          options: [],
          rules: [
            { required: true, message: '计分类别不能为空' },
          ]
        }
      }, {
        title: '量化指标',
        type: SheetInfoFormTypeEnum.select,
        key: 'methodCalculationId',
        depended: 'scoringCategoryId',
        placeholder: '请选择量化指标',
        config: {
          options: [],
          rules: [
            { required: true, message: '量化指标不能为空' },
          ]
        }
      }, {
        title: '金额',
        type: SheetInfoFormTypeEnum.inputNumber,
        key: 'amount',
        depended: 'methodCalculationId',
        placeholder: ' 请输入',
        config: {
          rules: [
            { required: true, message: '金额不能为空' },
          ],
          suffix: '万元',
          min: 0,
          max: 99999999,
          controls: false
        }
      }, {
        title: '科研分',
        type: SheetInfoFormTypeEnum.text,
        key: 'researchScore',
        depended: 'methodCalculationId',
        config: {
          rules: [
            { required: true, message: '科研分不能为空' },
          ],
          suffix: '分',
          min: 0,
          max: 99999999,
        }
      }]
    }
  },
  {
    title: '项目成果',
    type: SheetInfoFormTypeEnum.radio,
    key: 'outcomeFlag',
    width: 'calc(100% - 120px)',
    cValue: false,
    config: {
      options: [
        { title: '属于项目成果', value: true },
        { title: '不属于项目成果', value: false },
      ],
      rules: [
        { required: true, message: '项目成果不能为空' },
      ]
    }
  },
  {
    title: '合同',
    type: SheetInfoFormTypeEnum.file,
    key: 'contractFileList',
    width: 'calc(100% - 120px)',
    placeholder: '请上传',
    config: {
      rules: [
        { required: true, message: '合同不能为空' },
      ],
      imageList: [
      ]
    }
  }, {
    title: '到账凭证',
    type: SheetInfoFormTypeEnum.file,
    key: 'receiptVoucherFileList',
    width: 'calc(100% - 120px)',
    placeholder: '请上传',
    config: {
      rules: [
        { required: true, message: '到账凭证不能为空' },
      ],
    }
  }, {
    title: '附件',
    type: SheetInfoFormTypeEnum.file,
    key: 'fileList',
    width: 'calc(100% - 120px)',
    placeholder: '请上传',
    config: {
      rules: [
        // { required: true, message: '附件不能为空'},
      ],
    }
  },
  {
    title: '',
    type: 6,
    width: 'calc(100% - 120px)',
    key: 'fileTip',
    hidden: route.query.mode !== 'edit' && route.query.id
  },
  {
    title: '备注',
    type: SheetInfoFormTypeEnum.inputOrTextArea,
    width: 'calc(100% - 120px)',
    key: 'remark',
    placeholder: '请输入...',
    config: {
      type: 'textarea',
      maxLength: 500,
      showWordLimit: true,
    }
  },])


const ApprovalRef = ref()
// 审核意见
const approvalComponents = ref([
  {
    title: '审核意见',
    type: SheetInfoFormTypeEnum.inputOrTextArea,
    width: 'calc(100% - 83px)',
    key: 'description',
    labelWidth: '84px',
    placeholder: '请输入...',
    config: {
      type: 'textarea',
      rules: [
        { required: true, message: '审核意见不能为空' },
      ],
      sheetInfoRowMarginTop: '0px',
      maxLength: 500,
      showWordLimit: true,
      options: computed(() => dict[dictEnum.reviewOpinion] || [])
    }
  },
  {
    title: '相关附件',
    type: SheetInfoFormTypeEnum.file,
    key: 'fileList',
    labelWidth: '84px',
    placeholder: '请上传',
    config: {

    }
  },
])

// 全量的量化指标
const appraiseStandardList = ref<AppraiseStandardDTO[]>([])

// 成果表单编辑模式 (由query.mode==='edit'和(项目详情接口状态为待提交审核、审核不通过/新建))
const mode = computed(() => {
  if (route.query.mode === 'edit' || route.query.mode === 'preview') {
    return route.query.mode as unknown as string
  }else if(route.query.id){
    return 'preview'
  }else{
    return 'edit'
  }
})

// 设置为编辑
const setToEdit = (params?: any) => {
  // 修改参数
  const newQuery = {
    ...route.query,
    mode: 'edit',
    ...params,
  }
  router.replace({ query: newQuery })
}

// 设置为预览
const setToPreview = (params?: any) => {
  // 修改参数
  const newQuery = {
    ...route.query,
    mode: 'preview',
    ...params
  }
  router.replace({ query: newQuery })
}


// 项目列表
const { run: getList } = useRequest(getProjectListApi, {
  manual: true,
  onSuccess: (response) => {
    if (response) {
      projectList.value = response
      projectNameList.value = response?.map((i: ProjectBasePageVO) => {
        return {
          value: i?.projectName,
          title: i?.projectName
        }
      })
      projectCodeList.value = response?.map((i: ProjectBasePageVO) => {
        return {
          value: i?.projectCode,
          title: i?.projectCode
        }
      })
    }
  }
})

// 关闭当前页签
const closeCurrentTab = () => {
  proxy.$tab.closePage()
}

// 横向项目详情
const { run: getDetail, loading } = useRequest(getHorizontalDetailApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: HorizontalPageVO) => {
    if (response) {
      status.value = response.status!
      
      if (status.value === 5 && appraiseStandardList.value.filter(item => item.id === response['methodCalculationId']).length === 0) { // 审核状态：已登记
        const appraiseStandard = {
          ...response,
          typeName: response.typeName, // 计分类别
          title: response.quanIndicators,
          value: response.methodCalculationId,
          id: response.methodCalculationId,
          typeId: response.methodCalculationId,
          type: response.methodType,
          typeReal: response.methodTypeReal,
        }
        appraiseStandardList.value = [...appraiseStandardList.value, appraiseStandard]
      }

      // 成果信息表单可编辑状态 、成员表格可编辑状态、审核记录显示状态
      if (props.moduleType === 'mine' && [resultStatusEnum.resultCollegeUnPass, resultStatusEnum.resultWaitSubmit, resultStatusEnum.resultOfficeUnPass].includes(response.status!)) {
        setFormReadOnly(mode.value === 'preview')
        showAuditRecordTable.value = mode.value === 'preview'
      } else if((props.moduleType === 'college' && response.status! === resultStatusEnum.resultWaitCollegeAudit) || props.moduleType === 'office' && response.status! === resultStatusEnum.resultCollegePassWaitOfficeAudit){
        setFormReadOnly(mode.value === 'preview')
        showAuditRecordTable.value = mode.value === 'preview'
      }else{
        setFormReadOnly(true)
        showAuditRecordTable.value = true
      }


      const researchScoreOption = appraiseStandardList.value.filter(item => item.id === response['methodCalculationId']).length > 0 ? appraiseStandardList.value.filter(item => item.id === response['methodCalculationId'])[0] : undefined
      sheetComponents.value.forEach((component: SheetInfoComponent) => {
        // 组件赋值
        if (response[component.key]) {
          // 文件类型
          if (component.key === 'fileList' || component.key === 'receiptVoucherFileList' || component.key === 'contractFileList') {
            component.cValue = response[component.key]?.map((file) => {
              return {
                ...file,
                uid: file.fileId,
              }
            })
          } else {
            component.cValue = response[component.key]
          }
        }
        // 混合组件赋值(科研分)
        if (component.type === 99 && component.config && component.config.list) {
          component.config.list.forEach((subComponent: SheetInfoComponent) => {
            // 科研分的考核指标更新，此处兼容 计分类别
            if (subComponent.key === 'scoringCategoryId' && subComponent.config) {
              // 用于存储唯一标题的对象
              const uniqueTitles = []
              subComponent.config.options = appraiseStandardList.value.map((item: AppraiseStandardDTO) => {
                return {
                  title: item.typeName,
                  value: item.typeId,
                }
              }).filter(item => {
                // 状态：已登记；特殊处理 计分类别
                if (status.value === 5 && item.value === response['methodCalculationId']) { // 说明是更新后的考核指标，所以需要将已登记的考核指标回显到 考核指标 数组
                  return true
                }
                // 如果uniqueTitles中还没有这个title，则添加它并返回true
                if (!uniqueTitles[item.title]) {
                  uniqueTitles[item.title] = true
                  return true
                }
                // 如果已经有了这个title，则返回false
                return false
              })
            }
            // 特殊处理 计分类别，由于methodCalculationId依赖 计分类别
            if (subComponent.key === 'scoringCategoryId' && response['methodCalculationId'] && appraiseStandardList.value.filter(item => item.id === response['methodCalculationId']).length > 0) {
              subComponent.cValue = appraiseStandardList.value.filter(item => item.id === response['methodCalculationId'])[0]['typeId']
            } else {
              // 金额和科研分组件的判定，type === 5 则手输科研分，否则根据typeReal === 2| 3 手输金额，1则自动带出分数
              if (researchScoreOption) {
                if (subComponent.key === 'amount') { // 金额 amount
                  if (researchScoreOption.type === 5) {
                    subComponent.hidden = true
                  } else {
                    if (researchScoreOption.typeReal === 2 || researchScoreOption.typeReal === 3) {
                      subComponent.type = -1
                      subComponent.hidden = false
                      if (subComponent.config && subComponent.config.rules.length > 0) {
                        subComponent.config.rules[0].required = true
                      }
                    } else {
                      subComponent.hidden = true
                      if (subComponent.config && subComponent.config.rules.length > 0) {
                        subComponent.config.rules[0].required = false
                      }
                    }
                    if (subComponent.config) {
                      subComponent.config.suffix = researchScoreOption.unitEnum === 1 ? '元' : '万元'
                      subComponent.config.precision = researchScoreOption.unitEnum === 1 ? 2 : 6
                    } else {
                      subComponent.config = {}
                      subComponent.config.suffix = researchScoreOption.unitEnum === 1 ? '元' : '万元'
                      subComponent.config.precision = researchScoreOption.unitEnum === 1 ? 2 : 6
                    }
                  }
                } else if (subComponent.key === 'researchScore') { // 科研分 researchScore
                  if (researchScoreOption.type === 5) {
                    subComponent.type = -1
                    if (subComponent.config) {
                      subComponent.config.controls = false
                    } else {
                      subComponent.config = {}
                      subComponent.config.controls = false
                    }
                    if (subComponent.config && subComponent.config.rules.length > 0) {
                      subComponent.config.rules[0].required = true
                    }
                  } else {
                    subComponent.type = 3
                    if (subComponent.config && subComponent.config.rules.length > 0) {
                      subComponent.config.rules[0].required = false
                    }
                  }
                }
              }
              subComponent.cValue = response[subComponent.key]
            }
          })
        }
      })
      applyPerInfo.value = {
        departmentName: response.departmentName,
        accountCode: response.accountCode,
        accountName: response.accountName
      }
    }
  },
  // 请求失败
  onError: () => {
    setFormReadOnly(true)
    showAuditRecordTable.value = true
  },
})

/* 获取考核量化指标 */
const { runAsync: getAppraiseStandardList } = useRequest(appraiseStandardApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: AppraiseStandardDTO[]) => {
    if (response && response.length) {
      appraiseStandardList.value = response.map((item: AppraiseStandardDTO) => {
        return {
          ...item,
          title: item.name,
          value: item.id,
        }
      })
      sheetComponents.value.forEach((component: SheetInfoComponent) => {
        if (component.key === 'assessmentMethodId' && component.config && component.config.list) {
          component.config.list.forEach((subComponent: SheetInfoComponent) => {
            // 计分类别 typeName
            if (subComponent.key === 'scoringCategoryId' && subComponent.config) {
              // 用于存储唯一标题的对象
              const uniqueTitles = {}
              subComponent.config.options = response.map((item: AppraiseStandardDTO) => {
                return {
                  title: item.typeName,
                  value: item.typeId,
                }
              }).filter(item => {
                // 如果uniqueTitles中还没有这个title，则添加它并返回true
                if (!uniqueTitles[item.title]) {
                  uniqueTitles[item.title] = true
                  return true
                }
                // 如果已经有了这个title，则返回false
                return false
              })
            }
          })
        }
      })
    }
  },
  // 请求失败
  onError: () => {
  },
})

/* 查询科研分 */
const { runAsync: getResearchScore, loading: getResearchScoreLoading } = useRequest(getResearchScoreApi, {
  // false 为自动执行
  manual: true,
})


/* 删除详情 */
const { run: deleteDetail, loading: deleteLoading } = useRequest(deleteResultsManagementApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: AppStateChangeRespDTO) => {
    if (response.isSuccess) {
      closeCurrentTab()
    }
  },
  // 请求失败
  onError: () => {
  },
})


/* 更新详情 */
const { runAsync: updateDetail, loading: updateLoading } = useRequest(getHorizontalUpdateApi, {
  // false 为自动执行
  manual: true,
  debounceWait: 300,
  // 请求成功
  onSuccess: (response: AppStateChangeRespDTO) => {
    if (response.isSuccess) {
      // 更新成果
    }
  },
  // 请求失败
  onError: () => {
  },
})


/* 新增详情 */
const { runAsync: createDetail, loading: createLoading } = useRequest(getHorizontalCreateApi, {
  // false 为自动执行
  manual: true,
  debounceWait: 300,
  // 请求成功
  onSuccess: (response: AppStateChangeRespDTO) => {
    if (response.isSuccess) {
      // 新增成功
    }
  },
  // 请求失败
  onError: () => {
  },
})

/* 审核 */
const { runAsync: approveDetail, loading: approveLoading } = useRequest(approveResultsManagementApi, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (response: AppStateChangeRespDTO, _params) => {
    if (response.isSuccess) {
      const _paramsStatus = _params?.[0]?.status
      // 提交审核
      if (_paramsStatus === resultStatusEnum.resultWaitCollegeAudit) {
        if (_params?.[0]?.isSubmit) { //  创建切提交
          closeCurrentTab()
          setTimeout(() => {
            router.push({
              name: 'mine-horizontal-detail',
              query: { id: achvId.value, mode: 'preview' }
            })
            setTimeout(() => {
              ElMessage({
                message: '提交成功!',
                type: 'success',
              })
            }, 500)
          }, 100)
          return
        } else {
          ElMessage({
            message: '提交成功!',
            type: 'success',
            plain: true,
          })
        }
      } else if (_paramsStatus === resultStatusEnum.resultCollegePassWaitOfficeAudit || _paramsStatus === resultStatusEnum.resultSign) {
        ElMessage({
          message: '审核通过!',
          type: 'success',
          plain: true,
        })
      } else if (_paramsStatus === resultStatusEnum.resultCollegeUnPass || _paramsStatus === resultStatusEnum.resultOfficeUnPass) {
        ElMessage({
          message: '审核不通过!',
          type: 'success',
          plain: true,
        })
      }
      getDetail({ id: achvId.value })
      setToPreview({ id: achvId.value })
    }
  },
  // 请求失败
  onError: () => {
  },
})

// 设置成果信息form为只读/编辑模式  isReadOnly: true 只读 false 编辑
const setFormReadOnly = (isReadOnly: boolean) => {
  sheetComponents.value.forEach((component: SheetInfoComponent) => {
    // 模块为我的成果，且mode=edit时，进入编辑模式，否则进入预览模式（没有详情id，说明是新建）
    if (!isReadOnly && component.key === 'statisticalYear') {
      component.cValue = new Date().getFullYear()
    }
    if (component.config) {
      component.config.readonly = isReadOnly
    } else {
      component.config = {}
      component.config.readonly = isReadOnly
    }
    if (component.type === 99 && component.config && component.config.list) {
      component.config.list.map((subComponent: SheetInfoComponent) => {
        if (subComponent.config) {
          subComponent.config.readonly = isReadOnly
        } else {
          subComponent.config = {}
          subComponent.config.readonly = isReadOnly
        }
      })
    }
  })
}

// 审核校验
const approveForm = (type: 'approve' | 'disApprove') => {
  ApprovalRef.value.checkSheetFormValidate((errors) => {
    if (!errors) {
      if (type === 'approve') {
        showApprove.value = true
      } else {
        showDisApprove.value = true
      }
    }else{
      approvalComponents.value?.forEach((i) => {
        if (errors[0]?.reason?.[i?.key]) {
          ElMessage({
            message: errors[0]?.reason?.[i?.key]?.[0]?.message,
            type: 'error',
          })
        }
      })
    }
  })
}

// 审核通过
const approveEvent = () => {
  approveDetail({
    id: achvId.value as string,
    status: props.moduleType === 'college' ? resultStatusEnum.resultCollegePassWaitOfficeAudit : resultStatusEnum.resultSign,
    description: ApprovalRef.value.params.description,
    fileIds: ApprovalRef.value?.params?.fileList?.map((i) => i?.id)
  })
  showApprove.value = false
}

// 审核不通过
const disApproveEvent = () => {
  approveDetail({
    id: achvId.value as string,
    status: props.moduleType === 'college' ? resultStatusEnum.resultCollegeUnPass : resultStatusEnum.resultOfficeUnPass,
    description: ApprovalRef.value.params.description,
    fileIds: ApprovalRef.value?.params?.fileList?.map((i) => i?.id)
  })
  showDisApprove.value = false
}

// 编辑
const editForm = () => {
  setToEdit()
}

// 取消确认
const cancelFormEvent = () => {
  showCancelSave.value = false
  if (!achvId.value) {
    closeCurrentTab()
  } else if (achvId.value) {
    setToPreview()
  }
}


// 暂存
/**
 * 
 * @param isSubmitForm 用户提交<true 保存并提交审核 false 仅保存>
 * @param manageSubmit 管理员提交<true: 管理员提交保存后显示审核详情页>
 */
 const tempSaveForm = async (isSubmitForm?: boolean, manageSubmit?: boolean) => {
  const params = {}
  // 调整参数
  Object.assign(params, ResultsInfoRef.value?.params)
  params.receiptVoucherFile = params.receiptVoucherFileList?.map(i => i?.id)
  params.contractFile = params.contractFileList?.map(i => i?.id)
  params.fileIds = params.fileList?.map(i => i?.id) //  附件ids
  params.assessmentMethodId = appraiseStandardList.value.filter(item => item.id === params?.['methodCalculationId'])?.[0]?.['assessmentMethodId'] //  科研分指标
  // 更新
  if (achvId.value) {
    const res = await updateDetail({ ...params, achvId: achvId.value })
    if (res?.isSuccess) {
      // 保存（更新且提交审核）
      if (isSubmitForm) {
        return approveDetail({
          id: achvId.value,
          status: resultStatusEnum.resultWaitCollegeAudit,
        })
      }
      // setToPreview()
      if(manageSubmit){
        setToPreview()
      }else{
        getDetail({ id: achvId.value })
      }
      // 更新
      return ElMessage({
        message: '保存成功',
        type: 'success',
      })
    }

    // 新增
  } else {
    const res = await createDetail(params)
    if (res?.isSuccess) {
      achvId.value = res.id
      // 保存（新增且提交审核）
      if (isSubmitForm) {
        return approveDetail({ id: res.id, status: resultStatusEnum.resultWaitCollegeAudit, isSubmit: true })
      }
      // 创建完成
      closeCurrentTab()
      setTimeout(() => {
        router.push({
          name: 'mine-horizontal-detail',
          query: { id: res.id, mode: 'edit' }
        })
        setTimeout(() => {
          ElMessage({
            message: '创建成功',
            type: 'success',
          })
        }, 500)
      }, 100)

    }
  }
}

// 科研分中金额是否必填
function requiredAmount() {
  // 金额和科研分组件的判定，type === 5 则手输科研分，否则根据typeReal === 2| 3 手输金额，1则自动带出分数不显示金额
  const researchScoreOption = appraiseStandardList.value.filter(item => item.id === ResultsInfoRef.value.params['methodCalculationId']).length > 0 ? appraiseStandardList.value.filter(item => item.id === ResultsInfoRef.value.params['methodCalculationId'])[0] : undefined
  if (researchScoreOption?.type === 5) {
    return false
  } else {
    if (researchScoreOption?.typeReal === 2 || researchScoreOption?.typeReal === 3) {
      return true
    } else {
      return false
    }
  }
}

// 科研分是否必填
function requiredResearchScore() {
  // 金额和科研分组件的判定，type === 5 则手输科研分，否则根据typeReal === 2| 3 手输金额，1则自动带出分数不显示金额
  const researchScoreOption = appraiseStandardList.value.filter(item => item.id === ResultsInfoRef.value.params['methodCalculationId']).length > 0 ? appraiseStandardList.value.filter(item => item.id === ResultsInfoRef.value.params['methodCalculationId'])[0] : undefined
  if (researchScoreOption?.type === 5) {
    return true
  } else {
    return false
  }
}

/**
 * 提交校验
 * @param manageSubmit 审核管理账号提交保存
 */
 const submitForm = (manageSubmit: boolean = false) => {
  // 成果信息表单
  ResultsInfoRef.value.checkSheetFormValidate((errors) => {
    if (!errors) {
      if(manageSubmit){
        return tempSaveForm(false, true)
      }
      if (ResultsInfoRef.value.params['researchScoreFlag'] && ResultsInfoRef.value && !ResultsInfoRef.value.params['scoringCategoryId']) {
        ElMessage({
          message: '计分类别不能为空',
          type: 'error',
        })
      } else if (ResultsInfoRef.value.params['researchScoreFlag'] && ResultsInfoRef.value && !ResultsInfoRef.value.params['methodCalculationId']) {
        ElMessage({
          message: '量化指标不能为空',
          type: 'error',
        })
      } else if (ResultsInfoRef.value.params['researchScoreFlag'] && requiredAmount() && ResultsInfoRef.value && !ResultsInfoRef.value.params['amount']) {
        ElMessage({
          message: '金额不能为空',
          type: 'error',
        })
      } else if (ResultsInfoRef.value.params['researchScoreFlag'] && requiredResearchScore() && ResultsInfoRef.value && !ResultsInfoRef.value.params['researchScore']) {
        ElMessage({
          message: '科研分不能为空',
          type: 'error',
        })
      } else {
        showSubmitSave.value = true
      }
    }else{
      if (mode.value !== 'edit') {
        ResultsInfoRef.value.cancelSheetFormValidate()
      }
      sheetComponents.value?.forEach((i) => {
        if (errors[0]?.reason?.[i?.key]) {
          ElMessage({
            message: errors[0]?.reason?.[i?.key]?.[0]?.message,
            type: 'error',
          })
        }

        if (i.type === 99 && i.config && i.config.list) {
          i.config.list.forEach((subComponent: SheetInfoComponent) => {
            if (errors[0]?.reason?.[subComponent?.key]) {
              ElMessage({
                message: errors[0]?.reason?.[subComponent?.key]?.[0]?.message,
                type: 'error',
              })
            }
          })
        }
      })
    }
  })
}

// 提取附属组件，用于预览模式下的表格显示
const getMixedComponents = (component: SheetInfoComponent) => {
  const mixedComponents = sheetComponents.value.filter(item => item.type === 99).filter(item => item.depended === component.key) as SheetInfoComponent[]
  if (mixedComponents.length > 0) {
    const mixedSubComponents = mixedComponents[0].config?.list?.filter(item => !!ResultsInfoRef.value.params[item.key])
    return  mixedSubComponents ?? []
  } else {
    return []
  }
}


// 提交确认
const submitFormEvent = () => {
  showSubmitSave.value = false
  tempSaveForm(true)
}

// 删除确认
const deleteFormEvent = () => {
  showDeleteDetail.value = false
  deleteDetail({ id: achvId.value })
}

watch(
  () => route.query.id,
  async () => {
    try {
      await getAppraiseStandardList({}) // 这里必须要先拿到量化考核指标，为了兼容已登记状态下，被移除的量化指标的正常显示。
    } catch (error) {
      appraiseStandardList.value = []
    }
    getList({ projectNature: projectNatureEnum.projectNatureHorizontal, createdBy: userStore.id })
    if (route.query.id) {
      achvId.value = route.query.id
      getDetail({ id: route.query.id })
    } else {
      // 新增
      showAuditRecordTable.value = false  //  无记录
      status.value = 0
      setFormReadOnly(false)
    }
  }, {
  immediate: true
}
)

watch(
  () => ResultsInfoRef.value && ResultsInfoRef.value?.params,
  () => {
    if (ResultsInfoRef.value && ResultsInfoRef.value.params) {

      const params = ResultsInfoRef.value.params;
      // 遍历对象的每个键值对
      for (const key in params) {
        // 检查 key 是否是对象自身的属性（而不是从原型链继承的）
        if (params.hasOwnProperty(key)) {
          // 获取对应的值
          const value = params[key];
          // 检查值是否存在且不为空（这里的“不为空”定义可能因情况而异）
          // 例如，我们可能认为 null、undefined、空字符串、空数组等都是“空”的
          if (value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0)) {
            // 如果值存在且不为空，取消必填校验提示
            ResultsInfoRef.value.cancelSheetFormValidate(key)
          }
        }
      }

      const researchScoreOption = appraiseStandardList.value.filter(item => item.id === ResultsInfoRef.value.params['methodCalculationId']).length > 0 ? appraiseStandardList.value.filter(item => item.id === ResultsInfoRef.value.params['methodCalculationId'])[0] : undefined

      sheetComponents.value.forEach((component: SheetInfoComponent) => {
        // 科研分
        if (component.key === 'assessmentMethodId' && component.config && component.config.list) {
          component.config.list.forEach(async (subComponent: SheetInfoComponent) => {
            if (subComponent.key === 'methodCalculationId' && subComponent.config && subComponent.depended) {
              // 量化指标选项 name >> 算分使用id
              subComponent.config.options = appraiseStandardList.value.filter(item => item.typeId === ResultsInfoRef.value.params[subComponent.depended as string])
              if (subComponent.cValue !== ResultsInfoRef.value.params['methodCalculationId']) {
                // 计算并自动带出科研分
                const researchScore = await getResearchScore({ amount: ResultsInfoRef.value.params['amount'], methodCalculationId: ResultsInfoRef.value.params['methodCalculationId'] })
                ResultsInfoRef.value.params['researchScore'] = researchScoreOption && researchScoreOption.type !== 5 ? researchScore : undefined
              }
            }
            // 金额和科研分组件的判定，type === 5 则手输科研分，否则根据typeReal === 2| 3 手输金额，1则自动带出分数不显示金额
            if (researchScoreOption) {
              if (subComponent.key === 'amount') { // 金额 amount
                if (researchScoreOption.type === 5) {
                  subComponent.hidden = true
                } else {
                  if (researchScoreOption.typeReal === 2 || researchScoreOption.typeReal === 3) {
                    subComponent.type = -1
                    subComponent.hidden = false
                    if (subComponent.config && subComponent.config.rules.length > 0) {
                      subComponent.config.rules[0].required = true
                    }
                    // 计算并自动带出科研分
                    if (subComponent.cValue !== ResultsInfoRef.value.params['amount']) {
                      const researchScore = await getResearchScore({ amount: ResultsInfoRef.value.params['amount'], methodCalculationId: ResultsInfoRef.value.params['methodCalculationId'] })
                      ResultsInfoRef.value.params['researchScore'] = researchScoreOption && researchScoreOption.type !== 5 ? researchScore : undefined
                    }
                  } else {
                    subComponent.hidden = true
                    if (subComponent.config && subComponent.config.rules.length > 0) {
                      subComponent.config.rules[0].required = false
                    }
                  }
                  if (subComponent.config) {
                    subComponent.config.suffix = researchScoreOption.unitEnum === 1 ? '元' : '万元'
                    subComponent.config.precision = researchScoreOption.unitEnum === 1 ? 2 : 6
                  } else {
                    subComponent.config = {}
                    subComponent.config.suffix = researchScoreOption.unitEnum === 1 ? '元' : '万元'
                    subComponent.config.precision = researchScoreOption.unitEnum === 1 ? 2 : 6
                  }
                }
              }
              if (subComponent.key === 'researchScore') { // 科研分 researchScore
                if (researchScoreOption.type === 5) {
                  subComponent.type = -1
                  if (subComponent.config) {
                    subComponent.config.controls = false
                  } else {
                    subComponent.config = {}
                    subComponent.config.controls = false
                  }
                  if (subComponent.config && subComponent.config.rules.length > 0) {
                    subComponent.config.rules[0].required = true
                  }
                } else {
                  subComponent.type = 3
                  if (subComponent.config && subComponent.config.rules.length > 0) {
                    subComponent.config.rules[0].required = false
                  }
                }
              }
            }
          })
        }
        // 控制依赖组件的显隐
        // 依赖科研分
        if (component.depended === 'researchScoreFlag') {
          component.hidden = ResultsInfoRef.value.params[component.depended] && (mode.value === 'edit') ? false : true
        }
        component.cValue = ResultsInfoRef.value.params[component.key]
        if (component.type === 99 && component.config && component.config.list) {
          component.config.list.forEach((subComponent: SheetInfoComponent) => {
            if (subComponent.key) {
              subComponent.cValue = ResultsInfoRef.value.params[subComponent.key]
            }
          })
        }
      })
    }
  }, {
  immediate: true,
  deep: true
}
)

// 项目编号
watch(
  () => ResultsInfoRef.value?.params?.projectCode, (val) => {
    const selectProjectList = projectList.value?.filter((i) => i?.projectCode === val) || []
    const curProName = sheetComponents.value[1].cValue
    const hasCurProName = projectList.value?.filter((i) => i?.projectName === curProName)?.length
    const selectProName = selectProjectList?.[0]?.projectName
    if (selectProjectList?.length && selectProName !== curProName) { // 存在当前编号项目
      sheetComponents.value[1].cValue = selectProName
    } else if (!selectProjectList?.length && val && hasCurProName) {  //  不存在当前编号项目 && 编号不为空(用户自己输入) && 当前项目名不是手动输入 - 清空项目名
      sheetComponents.value[1].cValue = ''
    }
  })
// 项目名
watch(
  () => ResultsInfoRef.value?.params?.name, (val) => {
    const selectProjectList = projectList.value?.filter((i) => i?.projectName === val) || []
    const curProCode = sheetComponents.value[0].cValue
    const hasCurProName = projectList.value?.filter((i) => i?.projectCode === curProCode)?.length
    const selectProCode = selectProjectList?.[0]?.projectCode
    if (selectProjectList?.length && selectProCode !== curProCode) { // 存在当前名字项目
      sheetComponents.value[0].cValue = selectProCode
    } else if (!selectProjectList?.length && val && hasCurProName) {  //  不存在当前名字项目 && 名字不为空(用户自己输入) && 当前编号不是手动输入 清空项目编号
      sheetComponents.value[0].cValue = ''
    }
  })


onMounted(() => {
  achvId.value = route.query.id

  // 设置下拉输入框长度限制
  nextTick(() => {
    const projectCodeInput = ResultsInfoRef.value?.$el?.querySelector('.projectCodeClass .el-select__input');
    const projectNameInput = ResultsInfoRef.value?.$el?.querySelector('.projectNameClass .el-select__input');
    if (projectCodeInput) {
      projectCodeInput?.setAttribute("maxlength", 50)
    }
    if (projectNameInput) {
      projectNameInput?.setAttribute("maxlength", 50)
    }
  });
})
</script>

<template>
  <div v-loading="pageLoading" class="pb-[24px] bg-white px-[20px]">
    <StatusBar v-if="achvId" :status="status" class="mx-[-20px]" />
    <ApplicantInfo v-if="props.moduleType !== 'mine'" :first-content="applyPerInfo?.departmentName" :second-content="applyPerInfo?.accountCode"
      :third-content="applyPerInfo?.accountName" class="mx-[-20px]" />
    <ResultsInfo ref="ResultsInfoRef" :class="{ 'sheetInfoClass': mode !== 'edit' }" :singleRow="mode === 'edit'" :components="sheetComponents">
      <template #researchScoreFlag="{component}">
        <div class="flex flex-col" style="margin: -12px;">
          <div class="researchScore" :style="{ borderBottom: ResultsInfoRef.params[component.key] ? '1px solid #BEDAFF' : 'none', width: 'calc(100vw - 198px)' }">
            {{ component?.config?.options?.filter(radio => radio.value === ResultsInfoRef.params[component.key])[0].title }}
          </div>
          <div v-if="ResultsInfoRef.params[component.key]">
            <div v-for="(subComponent, index) in getMixedComponents(component)" :key="subComponent.key" class="researchScore" :style="{ borderBottom: index !== getMixedComponents(component).length - 1 ? '1px solid #BEDAFF' : 'none', color: subComponent.key === 'researchScore' ? '#F53F3F' : '#1D2129', fontWeight: subComponent.key === 'researchScore' ? 'bold' : 'normal' }">
              <span v-if="subComponent.type === 1 && subComponent.config && subComponent.config.options && subComponent.config.options.filter(option => option.value === ResultsInfoRef.params[subComponent.key]).length > 0">
                  {{ subComponent.config.options.filter(option => option.value === ResultsInfoRef.params[subComponent.key])[0].title }}
              </span>
              <span v-else>
                {{ ResultsInfoRef.params[subComponent.key] }}
              </span>
              {{ subComponent.config && subComponent.config.suffix ? subComponent.config.suffix : '' }}
            </div>
          </div>
        </div>
      </template>
      <template #fileTip>
        <div style="color: #606266;font-size: 12px;line-height: 16px;">
          请上传大小不超过 <b style="color: #f56c6c">100MB</b> 格式为 <b style="color: #f56c6c">doc/docx/xls/xlsx/txt/pdf/png/jpg/jpeg</b>
          的文件，最多上传20个文件
        </div>
      </template>
    </ResultsInfo>

    <div class="pt-[24px]" v-if="showAuditRecordTable && !pageLoading">
      <ResultAuditRecordTable :id="achvId" />
    </div>
    <!-- 审核可见 （学院待审核、科研待审核）-->

    <template
      v-if="(status === resultStatusEnum.resultWaitCollegeAudit && props.moduleType === 'college') || (status === resultStatusEnum.resultCollegePassWaitOfficeAudit && props.moduleType === 'office')">
      <div v-if="mode !== 'edit'">
        <ResultsInfo ref="ApprovalRef" :components="approvalComponents" section-title="审核意见" />
      </div>
      <div class="examine-bar">
        <template v-if="mode === 'edit'">
          <el-button  @click="showCancelSave = true">取消</el-button>
          <el-button  @click="submitForm(true)" type="primary">保存</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="editForm">编辑</el-button>
          <el-button @click="approveForm('disApprove')" type="danger" plain>审核不通过</el-button>
          <el-button type="primary" @click="approveForm('approve')">审核通过</el-button>
        </template>
      </div>
    </template>

    <!-- 个人可见 (待提交、科研不通过、学院不通过)-->
    <div
      v-else-if="props.moduleType === 'mine' && [resultStatusEnum.resultCollegeUnPass, resultStatusEnum.resultWaitSubmit, resultStatusEnum.resultOfficeUnPass].includes(status)"
      class="examine-bar">
      <el-button v-if="achvId && mode !== 'edit'" type="danger" @click="showDeleteDetail = true">删除</el-button>
      <el-button v-if="achvId && mode === 'preview'" type="primary" @click="editForm">编辑</el-button>
      <el-button v-if="mode === 'edit'" @click="showCancelSave = true">取消</el-button>
      <el-button v-if="mode === 'edit'" @click="tempSaveForm()">暂存</el-button>
      <el-button v-if="!achvId || status === resultStatusEnum.resultWaitSubmit" type="primary" @click="submitForm()">提交</el-button>
    </div>

    <DelConfirmModal v-if="showDeleteDetail" :visible="showDeleteDetail" text="是否确认删除？" ok-text="删除"
      @cancel="showDeleteDetail = false" @ok="deleteFormEvent" />
    <DelConfirmModal v-if="showCancelSave" :visible="showCancelSave" text="是否确认取消保存？" ok-text="确定"
      @cancel="showCancelSave = false" @ok="cancelFormEvent" />
    <DelConfirmModal v-if="showSubmitSave" :visible="showSubmitSave" text="是否确认提交？" ok-text="确定" ok-type="primary"
      @cancel="showSubmitSave = false" @ok="submitFormEvent" />
    <DelConfirmModal v-if="showDisApprove" :visible="showDisApprove" text="是否确认审核不通过" :loading="approveLoading"
      ok-text="审核不通过" @cancel="showDisApprove = false" @ok="disApproveEvent" />
    <DelConfirmModal v-if="showApprove" :visible="showApprove" text="是否确认审核通过？" ok-text="审核通过" :loading="approveLoading"
      ok-type="primary" @cancel="showApprove = false" @ok="approveEvent" />

    <div v-if="(props.moduleType === 'mine' && [resultStatusEnum.resultCollegeUnPass, resultStatusEnum.resultWaitSubmit, resultStatusEnum.resultOfficeUnPass].includes(status)) || (status === resultStatusEnum.resultWaitCollegeAudit && props.moduleType === 'college') || (status === resultStatusEnum.resultCollegePassWaitOfficeAudit && props.moduleType === 'office')" class="h-[56px] bg-white"></div>
  </div>
</template>

<style scoped lang="scss">
.specificRequirementRow {
  font-size: 12px;
  line-height: 16px;
  color: #86909C;
}

.examine-bar {
  border-top: 1px solid #E5E6EB;
  --at-apply: fixed bottom-0 left-0 right-0 h-[72px] flex items-center justify-center bg-white z-1999;

  :deep(.el-button) {
    height: 32px;
  }
}

.sheetInfoClass {
  .researchScore {
    padding: 12px;
    min-height: 46px;
  }
  :deep(.multiRowsClass) {
    border: 1px solid #BEDAFF;
    border-left: none;
    border-top: none;
  }
  :deep(.el-form) {
    border-left: 1px solid #BEDAFF;
    border-top: 1px solid #BEDAFF;
  }
  :deep(.el-form .el-form-item__label) {
    background-color: #F6FAFF;
    border-right: 1px solid #BEDAFF;
    padding-top: 14px;
    padding-bottom: 14px;
  }
  :deep(.el-form-item__label:before) {
    display: none;
  }
  :deep(.el-form-item__content) {
    padding: 12px;
    min-height: 46px;
  }
}
</style>